<template>
  <div class="page-container register">
    <div class="header">
      <van-icon name="arrow-left" @click="router.back()" />
    </div>
    
    <div class="content">
      <div class="logo">
        <div class="icon-wrapper">
          <div class="icon-group">
            <van-icon name="friends-o" class="icon-main" />
            <van-icon name="plus" class="icon-badge" />
          </div>
          <div class="icon-circle"></div>
        </div>
        <div class="platform-name">陪诊服务平台</div>
      </div>

      <div class="welcome">
        <p>填写信息完成注册</p>
      </div>

      <div class="form">
        <van-form @submit="onSubmit">
          <van-cell-group inset>
            <van-field
              v-model="formData.name"
              name="name"
              placeholder="请输入用户名"
              :rules="[{ required: true, message: '请输入用户名' },
              {
                pattern: /^\d{9}$/, // 正则表达式校验用户名格式
                message: '用户名必须为9位且不连续重复的纯数字',
              },
            ]"
            >
              <template #left-icon>
                <van-icon name="user-o" color="#666" size="20" />
              </template>
            </van-field>

            <van-field
              v-model="formData.nickname"
              name="nickname"
              placeholder="请输入昵称"
              :rules="[{ required: true, message: '请输入昵称' },
              {
                pattern: /^.{1,10}$/, // 正则表达式校验昵称格式
                message: '昵称长度不能超过10个字符',
              },
            ]"
            >
              <template #left-icon>
                <van-icon name="contact" color="#666" size="20" />
              </template>
            </van-field>
            
            <van-field
              v-model="formData.phone"
              name="phone"
              placeholder="请输入手机号"
              :rules="[{ required: true, message: '请输入手机号' }, // 必填校验
              {
                pattern: /^1[3-9]\d{9}$/, // 正则表达式校验手机号格式
                message: '请输入正确的手机号',
              }]"
            >
              <template #left-icon>
                <van-icon name="phone-o" color="#666" size="20" />
              </template>
            </van-field>

            <van-field
              v-model="formData.password"
              type="password"
              name="password"
              placeholder="请输入密码"
              :rules="[{ required: true, message: '请输入密码' },
              {
                pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/, // 正则表达式校验密码格式
                message: '密码必须包含字母和数字，且长度为8-16位',
              },
            ]"
            >
              <template #left-icon>
                <van-icon name="lock" color="#666" size="20" />
              </template>
            </van-field>

            <van-field
              v-model="formData.confirmPassword"
              type="password"
              name="confirmPassword"
              placeholder="请再次输入密码"
              :rules="[
                { required: true, message: '请再次输入密码' },
                { validator: validateConfirmPassword, message: '两次输入的密码不一致' }
              ]"
            >
              <template #left-icon>
                <van-icon name="passed" color="#666" size="20" />
              </template>
            </van-field>

            <van-field
              v-model="ageGroupText"
              is-link
              readonly
              name="picker"
              placeholder="点击选择年龄范围"
              @click="showPicker = true"
            >
              <template #left-icon>
                <van-icon name="cluster-o" color="#666" size="20" />
              </template>
            </van-field>

            <van-field
              v-model="formData.code"
              name="code"
              placeholder="请输入验证码"
              :rules="[{ required: true, message: '请输入验证码' }]"
            >
              <template #left-icon>
                <van-icon name="shield-o" color="#666" size="20" style="margin-top: 1.5vw;"/>
              </template>
              <template #right-icon>
                <img 
                  v-if="captchaUrl" 
                  :src="captchaUrl" 
                  class="captcha-img" 
                  @click="refreshCaptcha"
                  alt="验证码"
                />
              </template>
            </van-field>
          </van-cell-group>

          <van-popup v-model:show="showPicker" position="bottom">
            <van-picker
              :columns="columns"
              @confirm="onConfirm"
              @cancel="showPicker = false"
              title="选择年龄范围"
              show-toolbar
            />
          </van-popup>

          <div class="agreement">
            <van-checkbox v-model="formData.agreement" shape="square" icon-size="16">
              我已阅读并同意<span class="link" @click.stop="showAgreement">《用户协议》</span>和<span class="link" @click.stop="showPrivacy">《隐私政策》</span>
            </van-checkbox>
          </div>

          <div class="submit-btn">
            <van-button round block type="primary" native-type="submit">
              注册
            </van-button>
          </div>
        </van-form>

        <div class="login">
          已有账号？ <span @click="goToLogin">立即登录</span>
        </div>
      </div>
    </div>
  </div>

  <!-- 用户协议弹框 -->
  <van-popup
    v-model:show="agreementVisible"
    round
    position="bottom"
    :style="{ height: '70%' }"
  >
    <div class="popup-content">
      <div class="popup-header">
        <div class="popup-title">用户协议</div>
        <van-icon name="cross" @click="agreementVisible = false" />
      </div>
      <div class="popup-body">
        <div class="agreement-content">
          <h3>陪诊服务平台用户协议</h3>
          <p>欢迎您使用陪诊服务平台！</p>
          <h4>1. 服务内容</h4>
          <p>本平台提供医院就医陪诊等相关服务，包括但不限于预约陪诊、带跑取药等。</p>
          <h4>2. 用户权责</h4>
          <p>2.1 用户需要提供真实、准确的个人信息。</p>
          <p>2.2 用户应遵守相关法律法规和平台规则。</p>
          <h4>3. 服务规则</h4>
          <p>3.1 平台将尽最大努力确保服务的安全性和可靠性。</p>
          <p>3.2 用户应妥善保管账号信息，因用户原因导致的损失由用户自行承担。</p>
        </div>
      </div>
    </div>
  </van-popup>

  <!-- 隐私政策弹框 -->
  <van-popup
    v-model:show="privacyVisible"
    round
    position="bottom"
    :style="{ height: '70%' }"
  >
    <div class="popup-content">
      <div class="popup-header">
        <div class="popup-title">隐私政策</div>
        <van-icon name="cross" @click="privacyVisible = false" />
      </div>
      <div class="popup-body">
        <div class="agreement-content">
          <h3>隐私政策</h3>
          <p>我们重视您的隐私保护，承诺保护您的个人信息安全。</p>
          <h4>1. 信息收集</h4>
          <p>1.1 我们收集的信息包括：基本个人信息、位置信息等。</p>
          <p>1.2 我们仅收集必要的信息用于提供服务。</p>
          <h4>2. 信息使用</h4>
          <p>2.1 收集的信息仅用于提供和改进我们的服务。</p>
          <p>2.2 未经您的同意，我们不会向第三方分享您的个人信息。</p>
          <h4>3. 信息保护</h4>
          <p>3.1 我们采用业界标准的安全技术保护您的信息。</p>
          <p>3.2 我们定期审查信息安全措施以确保其有效性。</p>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { ref ,onMounted} from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast } from 'vant'
import { register, captcha } from '@/api/user'
import { useUserStore } from '@/stores/user'


// 页面加载时获取验证码
onMounted(() => {
  getCaptcha()
})

const router = useRouter()
const userStore = useUserStore()

const formData = ref({
  name: '',           // 用户名
  nickname: '',       // 昵称
  phone: '',         // 手机号
  code: '',          // 验证码
  password: '',      // 密码
  confirmPassword: '', // 确认密码
  agreement: false,   // 协议同意
  ageGroup: 0        // 年龄组（0：青少年，1：老年人）
})

const captchaUrl = ref('')

// 获取验证码
const getCaptcha = async () => {
  try {
    const res = await captcha()
    if (res.code === 200 && res.data) {
      captchaUrl.value = res.data.image
    } else {
      showToast('获取验证码失败')
    }
  } catch (error) {
    showToast('获取验证码失败')
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  formData.value.code = ''
  getCaptcha()
}

const showPicker = ref(false)
const ageGroupText = ref('青少年') // 默认显示文本

const columns = [
  { text: '青少年', value: 0 },
  { text: '老年人', value: 1 }
]

const onConfirm = (item) => {
  formData.value.ageGroup = item.selectedOptions[0]?.value
  ageGroupText.value = item.selectedOptions[0]?.text
  showPicker.value = false
}

const counting = ref(0)

const validateConfirmPassword = (value) => {
  return value === formData.value.password
}

const onSubmit = async () => {
  if (!formData.value.agreement) {
    showToast('请先同意用户协议和隐私政策')
    return
  }

  if (formData.value.password !== formData.value.confirmPassword) {
    showToast('两次输入的密码不一致')
    return
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(formData.value.phone)) {
    showToast('请输入正确的手机号')
    return
  }

  try {
    const loading = showLoadingToast({
      message: '注册中...',
      forbidClick: true,
    })

    const res = await register({
      username: formData.value.name,     // 使用name作为用户名
      password: formData.value.password,
      nickname: formData.value.nickname, // 使用nickname作为昵称
      phone: formData.value.phone,
      ageGroup: formData.value.ageGroup,
      captcha: formData.value.code      // 验证码
    })

    loading.close()

    if (res.code === 200) {
      showToast({
        message: '注册成功',
        type: 'success'
      })
      // 注册成功后跳转到登录页
      router.push({
        path: '/login',
        query: {
          username: formData.value.name // 传递用户名到登录页
        }
      })
    }
  } catch (error) {
    showToast({
      message: error.message || '注册失败',
      type: 'fail'
    })
    // 注册失败时刷新验证码
    refreshCaptcha()
  }
}

const goToLogin = () => {
  router.push('/login')
}

// 用户协议和隐私政策弹框控制
const agreementVisible = ref(false)
const privacyVisible = ref(false)

// 显示用户协议
const showAgreement = () => {
  agreementVisible.value = true
}

// 显示隐私政策
const showPrivacy = () => {
  privacyVisible.value = true
}
</script>

<style lang="scss" scoped>
.register {
  min-height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;

  .header {
    padding: 16px;
    
    .van-icon {
      font-size: 24px;
      color: #333;
      cursor: pointer;
      transition: opacity 0.2s;

      &:hover {
        opacity: 0.8;
      }
    }
  }

  .content {
    flex: 1;
    padding: 0 24px;
    display: flex;
    flex-direction: column;
    max-width: 400px;
    margin: 0 auto;
    width: 100%;

    .logo {
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .icon-wrapper {
        position: relative;
        width: 88px;
        height: 88px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 16px;
        
        .icon-group {
          position: relative;
          z-index: 1;

          .icon-main {
            font-size: 44px;
            color: var(--primary-color);
          }

          .icon-badge {
            position: absolute;
            right: -12px;
            bottom: -4px;
            font-size: 20px;
            color: #fff;
            background-color: var(--primary-color);
            border-radius: 50%;
            padding: 4px;
            box-shadow: 0 2px 8px rgba(11, 181, 132, 0.3);
          }
        }

        .icon-circle {
          position: absolute;
          width: 100%;
          height: 100%;
          border-radius: 50%;
          background: linear-gradient(135deg, rgba(11, 181, 132, 0.1), rgba(20, 211, 139, 0.1));
          animation: pulse 2s infinite;
        }

        &::after {
          content: '';
          position: absolute;
          width: 70px;
          height: 70px;
          border-radius: 50%;
          background: linear-gradient(135deg, rgba(11, 181, 132, 0.2), rgba(20, 211, 139, 0.2));
        }
      }

      .platform-name {
        font-size: 20px;
        font-weight: 500;
        color: var(--primary-color);
        letter-spacing: 1px;
        background: linear-gradient(to right, var(--primary-color), #14d38b);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }

    .welcome {
      margin-bottom: 20px;
      text-align: center;
      
      p {
        font-size: 16px;
        color: var(--text-color-secondary);
        margin: 0;
        letter-spacing: 0.5px;
      }
    }

    .form {
      .van-cell-group {
        margin-bottom: 24px;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        
        :deep(.van-field) {
          padding: 16px;

          .van-field__left-icon {
            margin-right: 12px;
          }

          .van-field__control {
            font-size: 16px;
            color: var(--text-color);

            &::placeholder {
              color: #999;
            }
          }
        }

        .captcha-img {
          height: 32px;
          border-radius: 4px;
          cursor: pointer;
          transition: opacity 0.2s;
          margin-right: 4px;
          display: flex;
          align-items: center;
          align-self: center;
          object-fit: contain;

          &:hover {
            opacity: 0.8;
          }
        }

        :deep(.van-field__right-icon) {
          height: 100%;
          display: flex;
          align-items: center;
          margin-right: 8px;
        }
      }

      .agreement {
        margin: 24px 0;
        padding: 0 4px;
        font-size: 14px;
        color: var(--text-color-secondary);
        display: flex;
        justify-content: center;

        .link {
          color: var(--primary-color);
          margin: 0 2px;
        }

        :deep(.van-checkbox__label) {
          color: var(--text-color-secondary);
        }
      }

      .submit-btn {
        margin-bottom: 32px;

        :deep(.van-button) {
          height: 48px;
          font-size: 16px;
          font-weight: 500;
          letter-spacing: 1px;
          background: linear-gradient(to right, var(--primary-color), #14d38b);
          border: none;
          transition: transform 0.2s;

          &:active {
            transform: scale(0.98);
          }
        }
      }

      .login {
        text-align: center;
        font-size: 14px;
        color: var(--text-color-secondary);

        span {
          color: var(--primary-color);
          margin-left: 4px;
          cursor: pointer;
          transition: opacity 0.2s;

          &:hover {
            opacity: 0.8;
          }
        }
      }
    }
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.popup-content {
  height: 100%;
  display: flex;
  flex-direction: column;

  .popup-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;

    .popup-title {
      font-size: 18px;
      font-weight: 500;
      color: var(--text-color);
    }

    .van-icon {
      font-size: 20px;
      color: #666;
      cursor: pointer;
      padding: 4px;
      
      &:hover {
        opacity: 0.8;
      }
    }
  }

  .popup-body {
    flex: 1;
    overflow-y: auto;
    padding: 20px;

    .agreement-content {
      h3 {
        font-size: 20px;
        font-weight: 500;
        color: var(--text-color);
        margin-bottom: 16px;
      }

      h4 {
        font-size: 16px;
        font-weight: 500;
        color: var(--text-color);
        margin: 16px 0 8px;
      }

      p {
        font-size: 14px;
        line-height: 1.6;
        color: var(--text-color-secondary);
        margin-bottom: 12px;
      }
    }
  }
}

.link {
  position: relative;
  z-index: 1;
}
</style> 